"use strict";

const Controller = require("egg").Controller;

class PdfController extends Controller {
  async index() {
    this.ctx.body = "hi, pdf";
  }

  beautyTable(item) {
    item.layout = {
      hLineWidth: function(i, node) {
        return 0.5;
      },
      vLineWidth: function(i, node) {
        return 0.5;
      },
      hLineColor: function(i, node) {
        return "#cacaca";
      },
      vLineColor: function(i, node) {
        return "#cacaca";
      }
    };

    let headerRowsCounter = item.table.headerRows;

    let tableBody = item.table.body;
    if (Array.isArray(tableBody)) {
      tableBody = tableBody.map((row, num) => {
        if (num < headerRowsCounter) {
          row = row.map(cell => {
            Object.prototype.toString.call(cell) === "[object Object]"
              ? (cell.fillColor = "#dedaec")
              : null;
            return cell;
          });
        } else {
          let start = num - headerRowsCounter;
          let odd = start % 2 !== 0;
          row = row.map(cell => {
            if (Object.prototype.toString.call(cell) === "[object Object]") {
              cell.fontSize = 6;
              if (odd) {
                cell.fillColor = "#f4f6fb";
              }
            }
            return cell;
          });
        }
        return row;
      });
    }
    return item;
  }

  //细化表格的线条，并且对表格启用隔行变色
  setLayoutRecursion(content) {
    return content.map(item => {
      if (item.columns !== undefined) {
        item.columns = this.setLayoutRecursion(item.columns);
      } else if (item.table !== undefined) {
        item = this.beautyTable(item);
      }
      return item;
    });
  }

  async create() {
    try {
      let pdfDefinition = this.ctx.request.body || {};
      pdfDefinition.content = this.setLayoutRecursion(pdfDefinition.content);
      var buffer = await this.ctx.service.pdf.create(pdfDefinition);
      this.ctx.response.body = buffer;
    } catch (e) {
      return Promise.reject({
        status: 500,
        message: "pdf生成产生错误!"
      });
    }
  }
}

module.exports = PdfController;
